//
//  ViewController.m
//  TwitterTest
//
//  Created by Sebastian Bene on 9/16/13.
//  Copyright (c) 2013 Proteste Ya. All rights reserved.
//

#import "ViewController.h"
#import <Social/Social.h>
#import <Accounts/Accounts.h>
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UITextField *textTweet;
@property (strong, nonatomic) IBOutlet UIButton *buttonTweet1;
@property (strong, nonatomic) IBOutlet UIButton *buttonTweet2;
@property (strong, nonatomic) IBOutlet UIButton *buttonTweet3;
@property (strong, nonatomic) IBOutlet UIButton *buttonTweet4;
@property (strong, nonatomic) IBOutlet UIButton *buttonGetTweet;
@property (strong, nonatomic) IBOutlet UIImageView *imageTweet;
@property (strong, nonatomic) IBOutlet UIButton *buttonGetTweetMap;
@property (strong, nonatomic) IBOutlet MKMapView *mapTweet;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// Tweet using TweetSheet
- (IBAction)TweetV1:(UIButton *)sender {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:_textTweet.text];
        [self presentViewController:tweetSheet animated:YES completion:nil];
    }
}
	
//Tweet using SLRequest
- (IBAction)TweetV2:(UIButton *)sender {
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    [account requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account
                                         accountsWithAccountType:accountType];
             
             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];
                 
                 NSDictionary *message = @{@"status": _textTweet.text};
                 
                 NSURL *requestURL = [NSURL
                                      
                                      URLWithString:@"http://api.twitter.com/1/statuses/update.json"];
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodPOST
                                           URL:requestURL parameters:message];
                 
                 postRequest.account = twitterAccount;
                 
                 [postRequest performRequestWithHandler:^(NSData *responseData,
                                                          NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      NSLog(@"Twitter HTTP response: %i", [urlResponse
                                                           statusCode]);
                  }];
             }
         }
     }];
}

//Tweet with image
- (IBAction)TweetV3:(UIButton *)sender {
    UIImage *image = [UIImage imageNamed:@"protesteya.jpg"];
    
    
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *twitterType =
    [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    
    SLRequestHandler requestHandler =
    ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        if (responseData) {
            NSInteger statusCode = urlResponse.statusCode;
            if (statusCode >= 200 && statusCode < 300) {
                NSDictionary *postResponseData =
                [NSJSONSerialization JSONObjectWithData:responseData
                                                options:NSJSONReadingMutableContainers
                                                  error:NULL];
                NSLog(@"[SUCCESS!] Created Tweet with ID: %@", postResponseData[@"id_str"]);
            }
            else {
                NSLog(@"[ERROR] Server responded: status code %d %@", statusCode,
                      [NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
            }
        }
        else {
            NSLog(@"[ERROR] An error occurred while posting: %@", [error localizedDescription]);
        }
    };
    
    ACAccountStoreRequestAccessCompletionHandler accountStoreHandler =
    ^(BOOL granted, NSError *error) {
        if (granted) {
            NSArray *accounts = [account accountsWithAccountType:twitterType];
            NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"
                          @"/1.1/statuses/update_with_media.json"];
            NSDictionary *params = @{@"status" : _textTweet.text};
            SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                                    requestMethod:SLRequestMethodPOST
                                                              URL:url
                                                       parameters:params];
            NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
            [request addMultipartData:imageData
                             withName:@"media[]"
                                 type:@"image/jpeg"
                             filename:@"image.jpg"];
            [request setAccount:[accounts lastObject]];
            [request performRequestWithHandler:requestHandler];
        }
        else {
            NSLog(@"[ERROR] An error occurred while asking for user authorization: %@",
                  [error localizedDescription]);
        }
    };
    
    [account requestAccessToAccountsWithType:twitterType
                                               options:NULL
                                            completion:accountStoreHandler];

}

//Tweet with location
- (IBAction)TweetV4:(UIButton *)sender {
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
    
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Error getting location");
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    _locationManager = nil;
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    NSString *latitude = [NSString stringWithFormat:@"%f", _locationManager.location.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", _locationManager.location.coordinate.longitude];
    
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    [account requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(), ^{
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account
                                         accountsWithAccountType:accountType];
             
             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];
                 
                 NSDictionary *message = @{@"status": _textTweet.text, @"lat":latitude, @"long":longitude, @"display_coordinates":@"true"};
                 
                 NSURL *requestURL = [NSURL
                                      URLWithString:@"http://api.twitter.com/1.1/statuses/update.json"];
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodPOST
                                           URL:requestURL parameters:message];
                 
                 postRequest.account = twitterAccount;
                 
                 [postRequest performRequestWithHandler:^(NSData *responseData,
                                                          NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      NSLog(@"Twitter HTTP response: %i", [urlResponse
                                                           statusCode]);
                  }];
             }
         }
         });
     }];
    
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    _locationManager = nil;
}

//Gets Tweet, loads text and image on screen
- (IBAction)GetTweet:(UIButton *)sender {
    self.mapTweet.hidden = YES;
        
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    [account requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account
                                         accountsWithAccountType:accountType];
             
             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];
                 
                 NSDictionary *message = @{@"id": @"380846840544911361", @"include_entities": @"true"};
                 
                 NSURL *requestURL = [NSURL
                                      URLWithString:@"https://api.twitter.com/1.1/statuses/show.json"];
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodGET
                                           URL:requestURL parameters:message];
                 
                 postRequest.account = twitterAccount;
                 
                 [postRequest performRequestWithHandler:^(NSData *responseData,
                                                          NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      NSDictionary *postResponseData =
                      [NSJSONSerialization JSONObjectWithData:responseData
                                                      options:NSJSONReadingMutableContainers
                                                        error:NULL];

                      self.textTweet.text = postResponseData[@"text"];
                      
                      NSString *urlImage = postResponseData[@"entities"][@"media"][0][@"media_url"];
                      
                      if(urlImage)
                      {
                          NSURL *imageURL = [NSURL URLWithString:urlImage];
                          NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
                          UIImage *image = [UIImage imageWithData:imageData];
                          
                          self.imageTweet.image = image;
                          
                          self.imageTweet.hidden = NO;
                      }
                      
                      NSLog(@"Twitter HTTP response: %i", [urlResponse
                                                           statusCode]);
                  }];
             }
         }
     }];

}

//Gets Tweet, loads text and map on screen
- (IBAction)GetTweetMap:(UIButton *)sender {
    self.imageTweet.hidden = YES;
    
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    [account requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account
                                         accountsWithAccountType:accountType];
             
             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];
                 
                 NSDictionary *message = @{@"id": @"380164903392518145", @"include_entities": @"true"};
                 
                 NSURL *requestURL = [NSURL
                                      URLWithString:@"https://api.twitter.com/1.1/statuses/show.json"];
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodGET
                                           URL:requestURL parameters:message];
                 
                 postRequest.account = twitterAccount;
                 
                 [postRequest performRequestWithHandler:^(NSData *responseData,
                                                          NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      NSDictionary *postResponseData =
                      [NSJSONSerialization JSONObjectWithData:responseData
                                                      options:NSJSONReadingMutableContainers
                                                        error:NULL];
                      
                      self.textTweet.text = postResponseData[@"text"];
                      
                      NSArray *coordinates = postResponseData[@"coordinates"][@"coordinates"];
                      
                      if(coordinates)
                      {
                          CLLocationCoordinate2D location;
                          location.latitude = [coordinates[1] doubleValue];
                          location.longitude = [coordinates[0] doubleValue];
                          
                          MKPointAnnotation *newAnnotation = [[MKPointAnnotation alloc] init];
                          newAnnotation.coordinate = location;
                          [self.mapTweet addAnnotation:newAnnotation];
                          
                          MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 500, 500);
                          [self.mapTweet setRegion:region animated:YES];
                          [self.mapTweet selectAnnotation:newAnnotation animated:YES];
                          
                          self.mapTweet.hidden = NO;
                      }
                      
                      
                      NSLog(@"Twitter HTTP response: %i", [urlResponse
                                                           statusCode]);
                  }];
             }
         }
     }];
}

@end
